<template>
  <div class="test-plans-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2 class="page-title">测试计划管理</h2>
        <p class="page-description">管理测试计划，跟踪测试执行进度</p>
      </div>
      <div class="header-right">
        <el-button 
          type="primary" 
          @click="handleCreate"
          v-if="hasPermission('test_case:create')"
        >
          <el-icon><Plus /></el-icon>
          新建测试计划
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="filter-section">
      <el-card shadow="never">
        <div class="filter-row">
          <div class="filter-left">
            <el-input
              v-model="filterForm.search"
              placeholder="搜索测试计划名称..."
              clearable
              style="width: 300px"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-select
              v-model="filterForm.project_id"
              placeholder="选择项目"
              clearable
              filterable
              style="width: 200px"
            >
              <el-option
                v-for="project in projectOptions"
                :key="project.id"
                :label="project.name"
                :value="project.id"
              />
            </el-select>
            <el-select
              v-model="filterForm.status"
              placeholder="选择状态"
              clearable
              style="width: 150px"
            >
              <el-option
                v-for="status in testPlanStatusOptions"
                :key="status.value"
                :label="status.label"
                :value="status.value"
              />
            </el-select>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleResetFilter">重置</el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 测试计划列表 -->
    <el-card shadow="never" class="table-card">
      <el-table
        v-loading="loading"
        :data="testPlans"
        stripe
        style="width: 100%"
        @row-click="handleRowClick"
        empty-text="暂无测试计划数据"
      >
        <el-table-column prop="name" label="计划名称" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            <el-link type="primary" @click.stop="handleView(row)" :underline="false">
              {{ row.name }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            <span v-if="row.description">{{ row.description }}</span>
            <span v-else class="text-placeholder">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="project_name" label="所属项目" width="150" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="执行进度" width="140">
          <template #default="{ row }">
            <div class="progress-cell">
              <div class="progress-text">
                <span class="progress-count">{{ row.executed_count || 0 }}</span>
                <span class="progress-separator">/</span>
                <span class="progress-total">{{ row.test_case_count || 0 }}</span>
              </div>
              <el-progress
                v-if="row.test_case_count > 0"
                :percentage="Math.round(((row.executed_count || 0) / row.test_case_count) * 100)"
                :stroke-width="8"
                :show-text="false"
                :color="getProgressColor(row)"
                class="progress-bar"
              />
              <span v-else class="no-progress">-</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="pass_rate" label="通过率" width="100">
          <template #default="{ row }">
            <span 
              v-if="row.pass_rate !== null && row.pass_rate !== undefined"
              :class="['pass-rate', getPassRateClass(row.pass_rate)]"
            >
              {{ row.pass_rate }}%
            </span>
            <span v-else class="text-placeholder">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="start_date" label="开始时间" width="160">
          <template #default="{ row }">
            {{ row.start_date ? formatDateTime(row.start_date) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="end_date" label="结束时间" width="160">
          <template #default="{ row }">
            {{ row.end_date ? formatDateTime(row.end_date) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="creator_name" label="创建人" width="120" />
        <el-table-column prop="created_at" label="创建时间" width="150" show-overflow-tooltip>
          <template #default="{ row }">
            <span style="white-space: nowrap;">{{ formatDateTime(row.created_at) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right" align="center">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button 
                type="primary" 
                size="small" 
                text 
                @click.stop="handleView(row)"
                class="action-btn"
              >
                查看
              </el-button>
              <el-button 
                type="primary" 
                size="small" 
                text 
                @click.stop="handleEdit(row)"
                v-if="canEditTestPlan(row)"
                class="action-btn"
              >
                编辑
              </el-button>
              <el-button 
                type="success" 
                size="small" 
                text 
                @click.stop="handleExecute(row)"
                v-if="!isCompletedStatus(row.status)"
                class="action-btn"
              >
                执行
              </el-button>
              <el-button 
                type="danger" 
                size="small" 
                text 
                @click.stop="handleDelete(row)"
                v-if="canDeleteTestPlan(row)"
                class="action-btn"
              >
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>


    <!-- 测试计划创建/编辑对话框 -->
    <el-dialog
      v-model="formDialogVisible"
      :title="formMode === 'create' ? '新建测试计划' : '编辑测试计划'"
      width="800px"
      @close="handleFormDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="计划名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入测试计划名称" />
        </el-form-item>
        <el-form-item label="计划描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入测试计划描述"
          />
        </el-form-item>
        <el-form-item label="所属项目" prop="project_id">
          <el-select
            v-model="formData.project_id"
            placeholder="选择项目"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="project in projectOptions"
              :key="project.id"
              :label="project.name"
              :value="project.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" prop="start_date">
          <el-date-picker
            v-model="formData.start_date"
            type="datetime"
            placeholder="选择开始时间"
            style="width: 100%"
            value-format="YYYY-MM-DDTHH:mm:ss"
            format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="end_date">
          <el-date-picker
            v-model="formData.end_date"
            type="datetime"
            placeholder="选择结束时间"
            style="width: 100%"
            value-format="YYYY-MM-DDTHH:mm:ss"
            format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="测试用例" prop="test_case_ids">
          <el-select
            v-model="formData.test_case_ids"
            multiple
            filterable
            placeholder="选择测试用例"
            style="width: 100%"
            :loading="testCasesLoading"
          >
            <el-option
              v-for="testCase in testCaseOptions"
              :key="testCase.id"
              :label="testCase.title"
              :value="testCase.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="formDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave" :loading="saving">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import {
  getTestPlans,
  createTestPlan,
  updateTestPlan,
  deleteTestPlan,
  type TestPlanListResponse,
  type TestPlanCreate,
  type TestPlanUpdate
} from '@/api/test-plan'
import { getTestCases } from '@/api/test-case'
import { useProjectStore } from '@/stores/project'
import { usePermission } from '@/hooks/usePermission'
import { formatDateTime } from '@/utils/date'
import { useRouter } from 'vue-router'
import { useStateStore } from '@/stores/state'
import { ModuleType } from '@/types/core'

const { hasPermission } = usePermission()
const projectStore = useProjectStore()
const router = useRouter()

// 响应式数据
const loading = ref(false)
const testPlans = ref<TestPlanListResponse[]>([])
const showAdvancedFilter = ref(false)

// 筛选表单
const filterForm = reactive({
  search: '',
  project_id: '',
  status: '' as 'pending' | 'executing' | 'completed' | ''
})

// 分页数据
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 选项数据
const projectOptions = ref<Array<{ id: string; name: string }>>([])
const testCaseOptions = ref<Array<{ id: string; title: string }>>([])
const testCasesLoading = ref(false)

// 对话框状态
const formDialogVisible = ref(false)
const formMode = ref<'create' | 'edit'>('create')
const saving = ref(false)

// 表单数据
const formRef = ref()
const formData = reactive<TestPlanCreate & { id?: string }>({
  name: '',
  description: '',
  project_id: '',
  start_date: '',
  end_date: '',
  status: 'pending',
  test_case_ids: []
})

const formRules = {
  name: [{ required: true, message: '请输入测试计划名称', trigger: 'blur' }],
  project_id: [{ required: true, message: '请选择项目', trigger: 'change' }]
}

// 计算属性
// 状态管理
const stateStore = useStateStore()

// 测试计划状态选项（从状态管理系统获取）
const testPlanStatusOptions = computed(() => {
  const states = stateStore.getStatesByModule(ModuleType.TEST_PLAN)
  return states.map(state => ({
    value: state.code,
    label: state.name
  }))
})

// 获取状态标签（从状态管理系统）
const getStatusLabel = (status: string) => {
  if (!status) return '-'
  const state = stateStore.getStateByCode(status, ModuleType.TEST_PLAN)
  return state?.name || status
}

// 获取状态标签类型（从状态管理系统）
const getStatusType = (status: string): 'success' | 'warning' | 'info' | 'danger' => {
  if (!status) return 'info'
  const state = stateStore.getStateByCode(status, ModuleType.TEST_PLAN)
  if (state) {
    // 根据颜色映射到Element Plus的tag type
    const colorMap: Record<string, 'success' | 'primary' | 'warning' | 'info' | 'danger'> = {
      '#67C23A': 'success',
      '#409EFF': 'primary',
      '#E6A23C': 'warning',
      '#F56C6C': 'danger',
      '#909399': 'info',
      '#52c41a': 'success',
      '#faad14': 'warning',
      '#d9d9d9': 'info'
    }
    return colorMap[state.color] || 'info'
  }
  return 'info'
}

// 检查是否为完成状态
const isCompletedStatus = (status: string): boolean => {
  if (!status) return false
  const state = stateStore.getStateByCode(status, ModuleType.TEST_PLAN)
  if (state) {
    const name = state.name || ''
    return name.includes('完成') || name.includes('已完成') || name.includes('completed')
  }
  return status === 'completed'
}

// 获取进度条颜色
const getProgressColor = (row: TestPlanListResponse) => {
  if (!row.test_case_count || row.test_case_count === 0) return '#e4e7ed'
  const percentage = Math.round(((row.executed_count || 0) / row.test_case_count) * 100)
  if (percentage >= 80) return '#67c23a'
  if (percentage >= 50) return '#e6a23c'
  return '#409eff'
}

// 获取通过率样式类
const getPassRateClass = (passRate: number) => {
  if (passRate >= 80) return 'pass-rate-high'
  if (passRate >= 60) return 'pass-rate-medium'
  if (passRate >= 40) return 'pass-rate-low'
  return 'pass-rate-very-low'
}

const formatDate = (date: string) => {
  if (!date) return '-'
  return date.split('T')[0]
}

const canEditTestPlan = (testPlan: TestPlanListResponse) => {
  return hasPermission('test_case:update') || hasPermission('*')
}

const canDeleteTestPlan = (testPlan: TestPlanListResponse) => {
  return hasPermission('test_case:delete') || hasPermission('*')
}

// 加载数据
const loadTestPlans = async () => {
  loading.value = true
  try {
    const params: any = {
      page: pagination.page,
      size: pagination.size
    }
    if (filterForm.search) {
      // 搜索功能需要后端支持，这里先不传
    }
    if (filterForm.project_id) {
      params.project_id = filterForm.project_id
    }
    if (filterForm.status) {
      params.status = filterForm.status
    }

    const result = await getTestPlans(params)
    console.log('测试计划列表响应:', result)
    testPlans.value = result.items || []
    pagination.total = result.total || 0
    pagination.page = result.page || 1
    pagination.size = result.size || 20
    console.log('设置后的测试计划列表:', testPlans.value)
  } catch (error: any) {
    console.error('加载测试计划失败:', error)
    ElMessage.error(error?.message || '加载测试计划失败')
    testPlans.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

const loadProjects = async () => {
  try {
    const projects = await projectStore.fetchProjects()
    if (Array.isArray(projects) && projects.length > 0) {
      projectOptions.value = projects.map((p: any) => ({
        id: p.value || p.id || String(p._id || ''),
        name: p.label || p.name || ''
      })).filter((p: any) => p.id && p.name)
    }
  } catch (error: any) {
    console.error('加载项目列表失败:', error)
    projectOptions.value = []
  }
}

const loadTestCases = async (projectId?: string) => {
  if (!projectId && !formData.project_id) return
  
  testCasesLoading.value = true
  try {
    const params: any = {
      page: 1,
      size: 100
    }
    if (projectId || formData.project_id) {
      params.project_id = projectId || formData.project_id
    }
    
    const result = await getTestCases(params)
    testCaseOptions.value = (result.items || []).map((tc: any) => ({
      id: tc.id,
      title: tc.title
    }))
  } catch (error: any) {
    console.error('加载测试用例失败:', error)
    testCaseOptions.value = []
  } finally {
    testCasesLoading.value = false
  }
}

// 事件处理
const handleSearch = () => {
  pagination.page = 1
  loadTestPlans()
}

const handleResetFilter = () => {
  filterForm.search = ''
  filterForm.project_id = ''
  filterForm.status = ''
  handleSearch()
}

const handleRowClick = (row: TestPlanListResponse) => {
  handleView(row)
}

const handleView = (testPlan: TestPlanListResponse) => {
  router.push(`/test-management/plans/${testPlan.id}`)
}

const handleCreate = () => {
  formMode.value = 'create'
  formData.name = ''
  formData.description = ''
  formData.project_id = ''
  formData.start_date = ''
  formData.end_date = ''
  formData.status = 'pending'
  formData.test_case_ids = []
  delete formData.id
  formDialogVisible.value = true
}

// 将后端返回的日期格式转换为 el-date-picker 需要的格式（YYYY-MM-DDTHH:mm:ss）
const normalizeDateForPicker = (dateStr: string | undefined): string => {
  if (!dateStr) return ''
  // 如果是 ISO 格式（YYYY-MM-DDTHH:mm:ss 或带时区），提取日期时间部分
  if (dateStr.includes('T')) {
    // 移除时区信息，只保留日期时间部分（YYYY-MM-DDTHH:mm:ss）
    return dateStr.split('+')[0].split('Z')[0]
  }
  // 如果是 YYYY-MM-DD 格式，补充时间部分
  if (/^\d{4}-\d{2}-\d{2}$/.test(dateStr)) {
    return `${dateStr}T00:00:00`
  }
  // 如果是 YYYY-MM-DD HH:mm:ss 格式，替换空格为 T
  if (/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(dateStr)) {
    return dateStr.replace(' ', 'T')
  }
  return dateStr
}

const handleEdit = (testPlan: TestPlanListResponse) => {
  formMode.value = 'edit'
  formData.id = testPlan.id
  formData.name = testPlan.name
  formData.description = testPlan.description || ''
  formData.project_id = testPlan.project_id
  formData.start_date = normalizeDateForPicker(testPlan.start_date)
  formData.end_date = normalizeDateForPicker(testPlan.end_date)
  formData.status = testPlan.status
  formData.test_case_ids = testPlan.test_case_ids || []
  formDialogVisible.value = true
  loadTestCases(testPlan.project_id)
}

const handleSave = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    saving.value = true
    
    // el-date-picker 的 value-format 已设置为 YYYY-MM-DDTHH:mm:ss，直接使用
    const submitData: any = {
      name: formData.name,
      description: formData.description || undefined,
      project_id: formData.project_id,
      start_date: formData.start_date || undefined,
      end_date: formData.end_date || undefined,
      status: formData.status as any,
      test_case_ids: formData.test_case_ids
    }
    
    if (formMode.value === 'create') {
      await createTestPlan(submitData as TestPlanCreate)
      ElMessage.success('创建测试计划成功')
    } else {
      if (!formData.id) return
      const updateData: TestPlanUpdate = {
        name: submitData.name,
        description: submitData.description,
        project_id: submitData.project_id,
        start_date: submitData.start_date,
        end_date: submitData.end_date,
        status: submitData.status,
        test_case_ids: submitData.test_case_ids
      }
      await updateTestPlan(formData.id, updateData)
      ElMessage.success('更新测试计划成功')
    }
    
    formDialogVisible.value = false
    await loadTestPlans()
  } catch (error: any) {
    if (error !== false) {
      console.error('保存测试计划失败:', error)
      ElMessage.error(error?.message || '保存失败')
    }
  } finally {
    saving.value = false
  }
}

const handleDelete = async (testPlan: TestPlanListResponse) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除测试计划 "${testPlan.name}" 吗？`,
      '确认删除',
      {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }
    )
    
    await deleteTestPlan(testPlan.id)
    ElMessage.success('删除成功')
    await loadTestPlans()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除测试计划失败:', error)
      ElMessage.error(error?.message || '删除失败')
    }
  }
}

const handleExecute = (testPlan: TestPlanListResponse) => {
  handleView(testPlan)
}

const handleFormDialogClose = () => {
  formRef.value?.resetFields()
}

const handleSizeChange = () => {
  loadTestPlans()
}

const handleCurrentChange = () => {
  loadTestPlans()
}

// 初始化
onMounted(async () => {
  await stateStore.fetchStates({ module_type: ModuleType.TEST_PLAN })
  await loadProjects()
  await loadTestPlans()
})
</script>

<style scoped lang="scss">
.test-plans-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 20px;
    padding: 0;
    
    .header-left {
      .page-title {
        margin: 0 0 8px 0;
        font-size: 24px;
        font-weight: 600;
        color: #303133;
        line-height: 1.2;
      }
      
      .page-description {
        margin: 0;
        font-size: 14px;
        color: #909399;
        line-height: 1.5;
      }
    }
    
    .header-right {
      :deep(.el-button) {
        border-radius: 6px;
        font-weight: 500;
      }
    }
  }
  
  .filter-section {
    margin-bottom: 16px;
    
    :deep(.el-card) {
      border-radius: 8px;
      border: 1px solid #e4e7ed;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
      
      .el-card__body {
        padding: 16px 20px;
      }
    }
    
    .filter-row {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .filter-left {
        display: flex;
        gap: 12px;
        align-items: center;
        flex-wrap: wrap;
        
        :deep(.el-input) {
          .el-input__wrapper {
            border-radius: 6px;
          }
        }
        
        :deep(.el-select) {
          .el-input__wrapper {
            border-radius: 6px;
          }
        }
        
        :deep(.el-button) {
          border-radius: 6px;
          font-weight: 500;
        }
      }
    }
  }
  
  .table-card {
    border-radius: 8px;
    border: 1px solid #e4e7ed;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
    
    :deep(.el-card__body) {
      padding: 20px;
    }
    
    :deep(.el-table) {
      font-size: 14px;
      
      .el-table__header-wrapper {
        th {
          background-color: #fafafa;
          color: #606266;
          font-weight: 600;
          height: 48px;
          padding: 12px 0;
        }
      }
      
      .el-table__body-wrapper {
        overflow-x: auto;
        
        tr {
          height: 64px;
          
          &:hover {
            background-color: #f5f7fa;
          }
        }
        
        td {
          padding: 12px 0;
        }
      }
      
      // 确保固定列正确显示
      .el-table__fixed-right {
        box-shadow: -2px 0 8px rgba(0, 0, 0, 0.08);
      }
      
      .el-table__fixed-right-patch {
        background-color: var(--el-table-bg-color);
      }
      
      // 链接样式
      .el-link {
        font-weight: 500;
        
        &:hover {
          text-decoration: underline;
        }
      }
    }
    
    .pagination-wrapper {
      margin-top: 20px;
      padding-top: 16px;
      border-top: 1px solid #e4e7ed;
      display: flex;
      justify-content: flex-end;
    }
  }
  
  // 进度单元格样式
  .progress-cell {
    display: flex;
    flex-direction: column;
    gap: 6px;
    
    .progress-text {
      display: flex;
      align-items: center;
      gap: 4px;
      font-size: 13px;
      color: #606266;
      
      .progress-count {
        font-weight: 600;
        color: #409eff;
      }
      
      .progress-separator {
        color: #c0c4cc;
      }
      
      .progress-total {
        color: #909399;
      }
    }
    
    .progress-bar {
      :deep(.el-progress-bar__outer) {
        border-radius: 4px;
        background-color: #f0f2f5;
      }
      
      :deep(.el-progress-bar__inner) {
        border-radius: 4px;
      }
    }
    
    .no-progress {
      color: #c0c4cc;
      font-size: 13px;
    }
  }
  
  // 通过率样式
  .pass-rate {
    font-weight: 600;
    font-size: 14px;
    
    &.pass-rate-high {
      color: #67c23a;
    }
    
    &.pass-rate-medium {
      color: #e6a23c;
    }
    
    &.pass-rate-low {
      color: #f56c6c;
    }
    
    &.pass-rate-very-low {
      color: #f56c6c;
    }
  }
  
  // 操作按钮样式
  .action-buttons {
    display: flex;
    gap: 8px;
    justify-content: center;
    align-items: center;
    flex-wrap: wrap;
    
    .action-btn {
      padding: 4px 12px;
      font-size: 13px;
      border-radius: 4px;
      
      &:hover {
        background-color: rgba(64, 158, 255, 0.1);
      }
    }
  }
  
  .text-placeholder {
    color: #c0c4cc;
    font-size: 14px;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .test-plans-container {
    padding: 12px;
    
    .filter-section {
      .filter-row {
        .filter-left {
          width: 100%;
          
          .el-input,
          .el-select {
            flex: 1;
            min-width: 120px;
          }
        }
      }
    }
    
    .table-card {
      :deep(.el-table) {
        font-size: 13px;
        
        .el-table__empty-block {
          padding: 60px 0;
          
          .el-table__empty-text {
            color: #909399;
            font-size: 14px;
          }
        }
      }
    }
  }
}
</style>

